package com.hanamaki.day1.day3;

import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.Calendar;
import java.util.Set;

public class Demo_cookies {
    //注册驱动
    WebDriver driver;
    @BeforeMethod
    public void setUp(){
        //注册本地火狐打开的位置
        System.setProperty("webdriver.gecko.driver", "C:\\Program Files\\Mozilla Firefox\\geckodriver.exe");
        //初始化
        driver = new FirefoxDriver();

    }

    /**
     * 操作的是Cookies
     */
    @Test
    public void test(){
        /*注册 浏览器打开的 资源路径*/
        driver.get("http://www.baidu.com");
        driver.manage().getCookies();
        Set<Cookie> cookies = driver.manage().getCookies();
        Cookie[] allCookies =new Cookie[cookies.size()];
        cookies.toArray(allCookies);
        //打印已有的cookie 数量 和 内容
        System.out.println("当前cookie集合的数量为:"+cookies.size());
        System.out.println("");
        for (int i = 0; i < allCookies.length; i++) {
            Cookie allCookie = allCookies[i];
            System.out.println("cookies 名称\t-"+ allCookie.getName());
            System.out.println("cookies 值\t-"+ allCookie.getValue());
            System.out.println("cookies所在域\t-"+allCookie.getDomain());
            System.out.println("cookies路径\t-"+allCookie.getPath());
            System.out.println("cookies过期时间\t-"+allCookie.getExpiry());
            System.out.println("");

        }
        java.util.Calendar calendar=java.util.Calendar.getInstance();
        calendar.add(Calendar.DATE,+1);
        java.util.Date date = calendar.getTime();

        //添加cookie
        Cookie newCookie = new Cookie("newcookie","新cookie值","baidu.com","",date);
        cookies.add(newCookie);
        System.out.println("新增的cookie的务期属性为：");
        System.out.println("cookie名称   -"+newCookie.getName());
        System.out.println("cookie值       -"+newCookie.getValue());
        System.out.println("cookie所在域  -"+newCookie.getDomain());
        System.out.println("cookie 路径  -"+newCookie.getPath());
        System.out.println("cookie 过期时间  -"+newCookie.getExpiry());
        System.out.println("");
        //添加后显示cookie 数量
        System.out.println("添加cookie后，cookie集合的数量为："+cookies.size());
        System.out.println("");
        //删除cookie,先找新添加的cookie,然后删除
        allCookies=new Cookie[cookies.size()];
        cookies.toArray(allCookies);
        cookies.remove(allCookies[allCookies.length-1]);
        //删除cookie后，显示cookie数量
        System.out.println("删除后，cookie后，cookie集合的数量为："+cookies.size());



    }
    @AfterMethod
    public void close(){
        driver.close();
    }
}
